<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
session_start();
class User extends CI_Controller {
	function __construct()
	{
		parent::__construct();
		$this->load->library("soap");
		$this->load->library('session');
		$this->load->helper('url');
		$this->load->library('pagination');
		$this->load->helper(array('form', 'url'));
		$this->load->helper('recaptcha_helper');
		$this->load->helper("text");
		@session_start();
	}


	public function index(){
		if($this->session->userdata('upname') == null){
			redirect('user/login');
		}else{

			$data['username'] = $this->session->userdata('upname');
			$this->load->view('user/dashboard',$data);
		}
	}



	public function product(){
		if($this->session->userdata('upid') == null){
			redirect('user/login');
		}else{
			$this->load->model("transms_model");
			$this->load->model('report_model');
			$this->load->model('chatbox_model');
			$this->load->model('user_model');
			$this->load->model('transms_model');
			$data['totaluser'] = $this->user_model->totaluser();
			$data['smsday'] = $this->transms_model->totalmotoday(date('d-m-Y'));
			$data['totalsms'] = $this->transms_model->totalmo();
			//--------------END Function ----------------------------------
			$this->load->model('catetype_model');
			$this->load->model('content_model');
			$data['alltype'] = $this->catetype_model->_showalltype();
			//$data['allcate'] = $this->catetype_model->showllcate();
			//---------------------------------POST
			if (isset($_REQUEST['submit'])) {
				// 				echo mime_content_type('C:\\Documents and Settings\\Pham Xuan Son\\Desktop\\cavang.apk');
				// 				die();
				$typeid = $this->input->post('typeid', true);
				$cateid = $this->input->post('cateid', true);
				$coins = $this->input->post('coins',true);
				$namecontent = $this->input->post('namecontent', true);
				$description = $this->input->post('description', true);
					
				$mypath= "./src/imagescontent";
				$image=  $this->do_upload_image($mypath,'images');
				$mypathfile= "./apps";
					
				$ifiles=  $this->do_upload_file($mypathfile,'ifiles');
				$ifiles2=  $this->do_upload_file($mypathfile,'ifiles_2');
				$ifiles3= $this->input->post('ifiles_3', true);
				$this->content_model->add_newcontent($cateid,$typeid,$namecontent,$description,$image,$coins,$ifiles,$ifiles2,$ifiles3,0,$this->session->userdata('upid'));
				redirect('admincp/sitecontent');
			}
			//------------------------------End POST
			// 			//hien thi chatbox-----------------------------------
			// 			$this->load->model('chatbox_model');
			// 			$config['base_url'] = site_url('home/page');
			// 			$config['total_rows'] = $this->chatbox_model->_totalchatbox();
			// 			$config['per_page'] = 10;
			// 			$config['uri_segment'] = 3;
			// 			$config['first_link'] = "Đầu";
			// 			$config['last_link'] = 'Cuối';
			// 			$data['chatbox'] = $this->chatbox_model->_showchatbox($config['per_page'],$this->uri->segment(3));
			// 			$this->pagination->initialize($config);
			// 			$data['pages'] = $this->pagination->create_links();
			// 			//--------------------------------------------------
			// 			$this->load->model('user_model');
			// 			$userid = $this->session->userdata('upid');
			// 			$data['userid'] = $this->session->userdata('upid');
			// 			$data['userdetails'] = $this->user_model->showaccount($userid);
			// 			$this->load->model('app_model');
			// 			$data['apps'] = $this->app_model->showapp();
			// 			if( $this->session->userdata('upid') <> null){
			// 				$data["ses"] = $this->session->userdata('upid');
			// 			}else {
			// 				$data["ses"] = null;
			// 			}

			// 			//Xử lý gắn Java Code ------------------------------------------------------------

			// 			$username = $this->session->userdata('upname');
			// 			if(file_exists('file/'.$username.'/Cliphot_'.$data["ses"].'.jar')){
			// 				$data["userapps"] = base_url('file/'.$username.'/Cliphot_'.$data["ses"].'.jar');
			// 			}else{
			// 				mkdir('file/'.$username, 0777);
			// 				//move file jar goc ra ngoai:---------------------------
			// 				$old = 'java.zip';
			// 				$new =  'file/'.$username.'/Cliphot_'.$data["ses"].'.zip';
			// 				copy($old, $new) or die("Unable to copy $old to $new.");
			// 				$oldpro = 'list.properties';
			// 				$newpro =  'file/'.$username.'/list.properties';
			// 				copy($oldpro, $newpro) or die("Unable to copy $oldpro to $newpro.");
			// 				//tao file properties

			// 				//$this->executeproperties();
			// 				$this->execute_properties($username,3);
			// 				//ket thuc tao file properties---------------------------
				
			// 				//Xu ly va tao file Jar----------------------------------
			// 				$zip = new ZipArchive();
			// 				if(($zip->open('file/'.$username.'/Cliphot_'.$data["ses"].'.zip', ZipArchive::CREATE))!==true){
			// 					die('Error: Unable to create zip file');
			// 				}
			// 				$zip->addFile('file/'.$username.'/list.properties','list.properties');
			// 				$zip->close();
			// 				//ket thuc xu ly tao file jar----------------------------
			// 				rename('file/'.$username.'/Cliphot_'.$data["ses"].'.zip', 'file/'.$username.'/Cliphot_'.$data["ses"].'.jar');
			// 				$data["userapps"] = base_url('file/'.$username.'/Cliphot_'.$data["ses"].'.jar');
			// 				//unlink('file/'.$username.'/sms.data');
			// 			}
			// 			$username = $this->session->userdata('upname');
			// 			// xóa file nếu đã tồn tại
			// 			if(file_exists($username.'.data')){
			// 				unlink($username.'.data');

			// 			}

			// 			//Kết thúc xử lý file ---------------------------------------------------------------
			// 			$this->load->model('post_model');
			// 			$data['notifications'] = $this->post_model->get_last();
			// 			$data['news'] = $this->post_model->get_last_article(10);
			$this->load->view('user/dashboard',$data);
		}
	}

	public function login($err=null){
		if(isset($_REQUEST['register'])){
			redirect("user/register");
		}
		if (isset($_REQUEST['submit'])) {
			$this->log();
			$username = $this->input->post('uname', true);
			$pass1 = $this->input->post('pass1', true);
			$this->load->model('user_model');
			$result = $this->user_model->checkuser($username,md5($pass1));
			if($result == null){
				redirect('user/login/'.rand(1,10));//l·ªói sai username ho·∫∑c pass
			}else {
				$user_detail = $this->user_model->showaccount($result);
				$user_detail = $user_detail[0];
				if ($user_detail->active == 1) {
					$_SESSION['upid']=$result;
					$this->session->set_userdata('upid', $result);
					$this->session->set_userdata('upname', $username);
					$this->session->set_userdata('usertype', $user_detail->usertype);
					switch ($user_detail->usertype) {
						case '1':
							//developer
							redirect('developer/sales_report');
							break;
						case '2':
							//Advertiser
							redirect('advertiser/manage_click');
// 							echo 'Advertiser132';
							break;
						case '3':
							//Publisher
							echo 'Publisher';
							break;
						default:
							//normal user
							redirect('home/index');
							echo ('a man');				
							break;
					}
				}
				else {
					redirect('home/index');
				}
			}
		}
			
		$data['shoutbox'] =0;
		$this->load->view('user/login',$data);
	}

	public function register($err=null){

		if($this->checkip() == 0){
			//redirect("http://store8x.com");
			$this->log();
			if(isset($_REQUEST['loginbtt'])){
				redirect("user/login");
			}
			if (isset($_REQUEST['submit'])) {

				$username = strip_tags($this->input->post('uname', true));
				$usertype = $this->input->post('usertype', true);
				$pass1 = strip_tags($this->input->post('pass1', true));
				//	$pass2 = strip_tags($this->input->post('pass2', true));
				$email = strip_tags($this->input->post('uemail', true));
				$ip_address=$this->input->ip_address();
				$string1 = $this->input->post('recaptcha_challenge_field',true);
				$string2= $this->input->post('recaptcha_response_field',true);
					
				//	if($this->checkCaptCha($string1, $string2) == true ){
				$phonenumber = $this->input->post('phonenumber',true);
				if(strlen($username) <> 0 ){
					if(strlen($phonenumber) <> 0){
						if(strval(intval($phonenumber)) == strval($phonenumber)){
							//if(strcmp($pass1,$pass2)==0){
							if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
								$this->load->model('user_model');
								if($this->user_model->_adduser($username,$pass1,$phonenumber,$email,$ip_address,$usertype) == 1){
									redirect('user/login');
								}else {
									redirect('user/register/User-Da-ton-tai');// ƒë√£ t·ªìn t·∫°i user n√†y
								}
							} else {
								redirect('user/register/Email-nhap_sai');
							}

							// 								}else {
							// 									redirect('user/register/Password-Khong-Trung-Nhau');// l·ªói kh√¥ng ƒë√∫ng pass
							// 								}
						}else{
							redirect('user/register/So-dien-thoai-nhap-sai');// l·ªói s·ªë ƒëi·ªán tho·∫°i ko ph·∫£i l√† s·ªë t·ª± nhi√™n
						}
					}else {
						redirect('user/register/Ban-Chua_nhap-Dien-Thoai'); // l·ªói kh√¥ng nh·∫≠p phone
					}
				}else {
					redirect('user/register/Ban-chua-nhap-ten-dang-nhap'); // l·ªói kh√¥ng nh·∫≠p username
				}
				//}
			}

			$data['caution'] = $err;
			if( $this->session->userdata('upid') <> null){
				$data["ses"] = $this->session->userdata('upid');
			}else {
				$data["ses"] = null;
			}
			$publickey = $this->config->item('public_recaptcha_key');
			$data['captcha'] = recaptcha_get_html($publickey);
			$this->load->model('post_model');
			$data['notifications'] = $this->post_model->get_last();
			$data['news'] = $this->post_model->get_last_article(10);
			$this->load->view('user/register',$data);
		}else{
			redirect('user/pending');
		}
	}

	public function banned(){
		if($this->checkip() == 1){
			$this->load->view('banned');
		}else{
			redirect('home/index');
		}
	}
	public function checkCaptCha($string1,$string2){
		$privatekey = $this->config->item('private_recaptcha_key');
		$resp = recaptcha_check_answer ($privatekey,
				$_SERVER["REMOTE_ADDR"],
				$string1,
				$string2);
		if (!$resp->is_valid) {
			return false;
		} else {
			return true;
		}
	}


	function do_upload_image($mypath,$filename){
		$config['upload_path'] = $mypath;
		$config['allowed_types'] = 'gif|jpg|png';
		$config['max_size']	= '20000';
		$this->load->library('upload', $config);
		if(isset($filename))
		{
			//echo $filename; die();
			if (!$this->upload->do_upload($filename))
			{
				$error = array('error' => $this->upload->display_errors());
				return NULL;
			}
			else
			{
				$data = array('upload_data' => $this->upload->data());
				$imagename = $this->upload->file_name;
				return $imagename;
			}
		}else {
			echo $this->upload->display_errors();
		}
	}

	function do_upload_file($mypath,$filename){
		$config['upload_path'] = $mypath;
		$config['allowed_types'] = 'jar|jad';
		$config['max_size']	= '500000';
		$this->load->library('upload', $config);
		if(isset($filename))
		{
			//echo $filename; die();
			if (!$this->upload->do_upload($filename))
			{
				$error = array('error' => $this->upload->display_errors());
				return NULL;
			}
			else
			{
				$data = array('upload_data' => $this->upload->data());
				$imagename = $this->upload->file_name;
				return $imagename;
			}
		}else {
			echo $this->upload->display_errors();
		}
	}


	public function logout(){
		$this->session->unset_userdata('upid');
		$this->session->unset_userdata('upname');
		$this->session->sess_destroy();
		redirect('user');
	}

	public function log(){
		$session_id = $this->session->userdata('session_id');
		$ip_address=$this->input->ip_address();
		$user_agent = $this->session->userdata('user_agent');
		date_default_timezone_set('Asia/Bangkok');
		$logday = date("d-m-Y");
		$logtime= date("h:i:s");
		$module = $this->router->method;
		$class = $this->router->class;
		$this->load->model('log_model');
		$this->log_model->add_log($session_id,$ip_address,$user_agent,$logday,$logtime,$module,$class,$this->session->userdata('upid'));
	}

	public function checkip(){
		$ip_address=$this->input->ip_address();
		$this->load->model('log_model');
		return $this->log_model->checkip($ip_address);
	}


	function removesign($str)
	{
		$coDau=array("à","á","ạ","ả","ã","â","ầ","ấ","ậ","ẩ","ẫ","ă","ằ","ắ"
				,"ặ","ẳ","ẵ","è","é","ẹ","ẻ","ẽ","ê","ề","ế","ệ","ể","ễ","ì","í","ị","ỉ","ĩ",
				"ò","ó","ọ","ỏ","õ","ô","ồ","ố","ộ","ổ","ỗ","ơ"
				,"ờ","ớ","ợ","ở","ỡ",
				"ù","ú","ụ","ủ","ũ","ư","ừ","ứ","ự","ử","ữ",
				"ỳ","ý","ỵ","ỷ","ỹ",
				"đ",
				"À","Á","Ạ","Ả","Ã","Â","Ầ","Ấ","Ậ","Ẩ","Ẫ","Ă"
				,"Ằ","Ắ","Ặ","Ẳ","Ẵ",
				"È","É","Ẹ","Ẻ","Ẽ","Ê","Ề","Ế","Ệ","Ể","Ễ",
				"Ì","Í","Ị","Ỉ","Ĩ",
				"Ò","Ó","Ọ","Ỏ","Õ","Ô","Ồ","Ố","Ộ","Ổ","Ỗ","Ơ"
				,"Ờ","Ớ","Ợ","Ở","Ỡ",
				"Ù","Ú","Ụ","Ủ","Ũ","Ư","Ừ","Ứ","Ự","Ử","Ữ",
				"Ỳ","Ý","Ỵ","Ỷ","Ỹ",
				"Đ","ê","ù","à");
		$khongDau=array("a","a","a","a","a","a","a","a","a","a","a"
				,"a","a","a","a","a","a",
				"e","e","e","e","e","e","e","e","e","e","e",
				"i","i","i","i","i",
				"o","o","o","o","o","o","o","o","o","o","o","o"
				,"o","o","o","o","o",
				"u","u","u","u","u","u","u","u","u","u","u",
				"y","y","y","y","y",
				"d",
				"A","A","A","A","A","A","A","A","A","A","A","A"
				,"A","A","A","A","A",
				"E","E","E","E","E","E","E","E","E","E","E",
				"I","I","I","I","I",
				"O","O","O","O","O","O","O","O","O","O","O","O"
				,"O","O","O","O","O",
				"U","U","U","U","U","U","U","U","U","U","U",
				"Y","Y","Y","Y","Y",
				"D","e","u","a");
		return str_replace($coDau,$khongDau,$str);
	}





	public function execute_properties($username,$typeapp){
		$this->load->model('service_model');
		$numbersms = $this->service_model->show_services_number($typeapp);
		$numbercode = "";
		$prefix_1  = "";
		foreach($numbersms as $sms){
			$numbercode = $sms->shortcode;
			$prefix_1 = $sms->prefix_1;
		}
		$fname ='file/'.$username.'/list.properties';
		$fhandle = fopen($fname,"r");
		$content = fread($fhandle,filesize($fname));

		$content = str_replace("8785",$numbercode, $content);
		$content = str_replace("B12 346 Xem Clip Gai Xinh",$prefix_1." ".rand(10,300)." ".$username,$content);
		$content = str_replace("B12 346 Xem Clip Hot",$prefix_1." ".rand(10,300)." ".$username,$content);
		$content = str_replace("B12 346 Xem Clip Hai Uoc",$prefix_1." ".rand(10,300)." ".$username,$content);
		$content = str_replace("B12 346 Xem Clip Chuyen La",$prefix_1." ".rand(10,300)." ".$username,$content);
		$content = str_replace("B12 346 Xem Clip Hoat Hinh",$prefix_1." ".rand(10,300)." ".$username,$content);
		$content = str_replace("B12 346 Dang Ky Xem Clip 03 Ngay",$prefix_1." ".rand(10,300)." ".$username,$content);
			
		$fhandle = fopen($fname,"w");
		fwrite($fhandle,$content);
		fclose($fhandle);

	}

	//function tao file properties
	public function executeproperties(){
		$this->load->model('service_model');
		$rowwithtype = $this->service_model->get_servicescommand(1);
		$username = $this->session->userdata('upname');
		$commandcode = "";
		$shortcode = "";
		foreach($rowwithtype as $row){
			$commandcode = $row->prefix_1;
			$shortcode = $row->shortcode;
		}
		//echo $commandcode.'-'.$shortcode; die();
		$fh = fopen($username.'.data', 'w') or die("can't open file");

		$stringData = $commandcode.' '.rand(1,9999).' '.$username.'|'.$shortcode;
		fwrite($fh, $stringData);
		fclose($fh);
	}
	function info() {
		if ($this->session->userdata('usertype') == 1) {
				redirect('developer/sales_report');
		}
	}
}